using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace AutoTest.Core.Domain.TestRunning
{
    public class NUnitParser : INUnitParser
    {
        public TestRunCompletedMessage Parse(string outputFromNUnit)
        {
            var countsRegex = new Regex(@"Tests run: (?<TestsRun>[0-9]+), Errors: (?<Errors>[0-9]+), Failures: (?<Failures>[0-9]+), Inconclusive: (?<Inconclusive>[0-9]+)");
            var countsMatches = countsRegex.Match(outputFromNUnit);

            var results = new TestRunCompletedMessage();
            results.NumberOfTestsRun = ParseInt(countsMatches.Groups["TestsRun"]);
            results.NumberOfFailures = ParseInt(countsMatches.Groups["Errors"]) + ParseInt(countsMatches.Groups["Failures"]) +
                                       ParseInt(countsMatches.Groups["Inconclusive"]);

            var failuresRegex = new Regex(@"Test Failure : (?<TestName>.*)\n(?<ShortMessage>.*)\n");
            var failuresMatches = failuresRegex.Matches(outputFromNUnit);

            foreach (Match match in failuresMatches)
            {
                var testFailure = new TestFailure();
                testFailure.FullyQualifiedTestName = match.Groups["TestName"].Value.Trim();
                testFailure.ShortMessage = match.Groups["ShortMessage"].Value.Trim();
                if (testFailure.ShortMessage.StartsWith("[exec]"))
                    testFailure.ShortMessage = testFailure.ShortMessage.Substring("[exec]".Length).Trim();
                results.Failures.Add(testFailure);
            }

            return results;
        }

        private static int ParseInt(Group group)
        {
            if (!group.Success)
                return 0;

            return int.Parse(group.Value);
        }
    }
}